<template>
  <view class="container">
    <!-- 使用封装的侧边栏组件 -->
    <the-sidebar
      :is-open.sync="isSidebarOpen"
      :active-category="activeCategoryId"
      :menu-items="sidebarMenuItems"
      @select-category="handleCategorySelect"
      @delete-category="handleDeleteCategory"
      @add-category="handleAddCategory"
      @navigate-to-edit="navigateToEditPage"
    />

    <!-- Header -->
    <view class="header">
      <view class="menu-icon" @click="openSidebar">
        <image src="@/static/svg/menu.svg" mode="aspectFit"></image>
      </view>
      <view class="title" v-if="categoryItem">
        <image class="title-icon" :src="getIconPath(categoryItem.icon)" mode="aspectFit"></image>
        <text>{{categoryItem.text}}</text>
      </view>
      <view class="title" v-else>
        <text>加载中...</text>
      </view>
      <view class="more-icon">
        <image src="@/static/svg/more.svg" mode="aspectFit"></image>
      </view>
    </view>

    <!-- Task Type Tabs and Search Bar in One Row -->
    <view class="filter-row">
      <!-- Search Bar -->
      <view class="search-bar">
        <image
          class="search-icon"
          src="@/static/svg/search.svg"
          mode="aspectFit"
        ></image>
        <text class="search-placeholder">搜索</text>
      </view>
      <!-- Task Type Tabs -->
      <view class="task-tabs" v-if="false">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'todo' }"
          @click="switchTab('todo')"
        >
          <text>待办</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'done' }"
          @click="switchTab('done')"
        >
          <text>已完成</text>
        </view>
      </view>
    </view>

    <!-- Empty State -->
    <EmptyState
      :imageSrc="emptyImageSrc"
      :title="emptyStateTitle"
      :description="emptyStateDesc"
      :buttonText="'试试这些事情'"
      @clickAction="tryExamples"
    ></EmptyState>

    <!-- Floating Action Button -->
    <view class="fab" @click="addTask">
      <text class="fab-icon">+</text>
    </view>
  </view>
</template>

<script>
import TheSidebar from "@/components/custom/TheSidebar.vue";
import EmptyState from "@/components/custom/EmptyState.vue";
import { mapGetters, mapActions } from "vuex";
import { getIconPath } from '@/utils/iconUtils';

export default {
  name: "Activity",
  components: {
    TheSidebar,
    EmptyState
  },
  data() {
    return {
      activeTab: "todo",
      activityList: [],
      isSidebarOpen: false,
      title: "全部",
      categoryItem: {
        id: "",
        text: "加载中...",
        icon: "e10"
      },
    };
  },
  computed: {
    ...mapGetters("categories", [
      "getAllCategories",
      "getActiveCategory",
      "getCategoryById"
    ]),
    // 获取侧边栏菜单项（使用getAllCategories替代旧的getSidebarMenuItems）
    sidebarMenuItems() {
      // 将categories映射为侧边栏菜单项
      return this.getAllCategories.map(category => ({
        id: category.id,
        text: category.text,
        fixed: category.fixed || false,
        protected: category.protected || false,
        icon: category.icon
      }));
    },
    // 获取当前分类ID (用于TheSidebar组件，它期望一个字符串)
    activeCategoryId() {
      return this.getActiveCategory ? this.getActiveCategory.id : null;
    },
    // 获取当前分类对象
    activeCategory: {
      get() {
        return this.getActiveCategory;
      },
      set(category) {
        // 接收完整category对象并设置为当前活动分类
        if (category && typeof category === 'object') {
          this.$store.dispatch("categories/setActiveCategory", category);
        }
      },
    },
    emptyStateTitle() {
      return this.activeTab === "todo" ? "有哪些学习任务?" : "还没有完成的任务";
    },
    emptyStateDesc() {
      return this.activeTab === "todo"
        ? "不管是答题、背单词还是考研，如果认真完成挑战，点击右下角+即可添加"
        : "继续加油，完成更多学习任务吧！";
    },
    // 获取空状态图片
    emptyImageSrc() {
      return require("@/static/svg/study.svg");
    },
  },
  created() {
    // 初始化已有默认categoryItem，设置加载状态
    
    // 初始化分类数据
    this.$store.dispatch("categories/initCategories").then(() => {
      // 初始化完成后设置默认的当前分类
      if (this.getActiveCategory) {
        this.categoryItem = { 
          id: this.getActiveCategory.id || "",
          text: this.getActiveCategory.text || "未命名分类",
          icon: this.getActiveCategory.icon || "e10"
        };
     
      } else if (this.getAllCategories && this.getAllCategories.length > 0) {
        // 如果没有活动分类，默认使用第一个
        const defaultCategory = this.getAllCategories[0];
        if (defaultCategory) {
          this.categoryItem = {
            id: defaultCategory.id || "", 
            text: defaultCategory.text || "未命名分类",
            icon: defaultCategory.icon || "e10"
          };
         
          // 直接使用setter设置完整对象
          this.activeCategory = defaultCategory;
        }
      }
    }).catch(err => {
      console.error('初始化分类数据失败', err);
    });
    
    // 监听分类更新事件
    uni.$on("update-categories", this.handleCategoriesUpdate);
  },
  destroyed() {
    // 移除事件监听
    uni.$off("update-categories", this.handleCategoriesUpdate);
  },

  methods: {
    ...mapActions("categories", ["setActiveCategory", "saveCategories"]),

    // 获取图标完整路径
    getIconPath(iconName) {
      if (!iconName) return getIconPath("e10");
      return getIconPath(iconName);
    },

    // 处理分类更新事件
    handleCategoriesUpdate(categories) {
      if (!categories || !Array.isArray(categories)) {
        console.warn('接收到无效的分类数据');
        return;
      }
      
      // 检查当前选择的分类是否仍然存在
      const currentCategoryId = this.activeCategoryId;
      if (!currentCategoryId) return;
      
      const currentCategoryExists = categories.some(
        (cat) => cat && cat.id === currentCategoryId
      );

      // 如果当前选择的分类不存在了，默认选择第一个分类
      if (!currentCategoryExists && categories.length > 0) {
        console.log(
          `当前选择的分类 ${currentCategoryId} 已被删除，切换到默认分类`
        );
        const defaultCategory = categories.find(cat => cat && cat.fixed) || categories[0];
        if (defaultCategory) {
          this.activeCategory = defaultCategory;
          this.categoryItem = {
            id: defaultCategory.id || "",
            text: defaultCategory.text || "未命名分类",
            icon: defaultCategory.icon || "e10"
          };
        }
      }
    },

    switchTab(tab) {
      this.activeTab = tab;
    },
    // 打开侧边栏
    openSidebar() {
      this.isSidebarOpen = true;
    },
    // 处理分类选择事件
    handleCategorySelect(category) {
      // 查找完整的category对象
      const fullCategory = this.getAllCategories.find(c => c.id === category.id);
      if (fullCategory) {
        // 直接设置完整对象
        this.activeCategory = fullCategory;
        this.categoryItem = {
          id: category.id || "",
          text: category.text || "未命名分类",
          icon: category.icon || "e10"
        };
        this.isSidebarOpen = false;
        
        console.log(`加载${category.text}分类的数据`);
      }
    },

    navigateToEditPage() {
      // 导航到分类编辑页面
      uni.navigateTo({
        url: "/pages/activity/category-edit",
        success: () => {
          console.log("导航到分类编辑页面");
        },
      });
    },

    tryExamples() {
      console.log("Try examples clicked");
    },

    addTask() {
      console.log("Add task clicked");
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 150rpx);
  background-color: #f5f7fa;
  position: relative;
  padding-bottom: 50rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
}

/* 将任务标签和搜索框放在同一行 */
.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx 15rpx;
}

/* Task Type Tabs */
.task-tabs {
  display: flex;
  margin-left: 18rpx;
  width: 200rpx;
}

.tab-item {
  position: relative;
  padding: 15rpx 4rpx;
  margin-right: 15rpx;
  color: #666;
  font-size: 30rpx;
}

.tab-item.active {
  color: #4e6ef2;
  font-weight: 500;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30rpx;
  height: 6rpx;
  background-color: #4e6ef2;
  border-radius: 3rpx;
}

/* 搜索栏样式修改 */
.search-bar {
  flex: 1;
  height: 70rpx;
  background-color: #eff2f5;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.search-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 10rpx;
}

.search-placeholder {
  color: #999;
  font-size: 26rpx;
}

.menu-icon,
.more-icon {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-icon image,
.more-icon image {
  width: 40rpx;
  height: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.title-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
  vertical-align: middle;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  flex: 1;
}

.empty-image {
  width: 280rpx;
  height: 280rpx;
  background-color: #e8ebf3;
  border-radius: 50%;
  margin-bottom: 30rpx;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-image image {
  width: 180rpx;
  height: 180rpx;
}

.empty-title {
  font-size: 34rpx;
  font-weight: 500;
  margin-bottom: 15rpx;
  display: block;
  text-align: center;
}

.empty-desc {
  font-size: 28rpx;
  color: #888;
  text-align: center;
  line-height: 1.5;
  display: block;
}

.try-button {
  margin-top: 40rpx;
  background-color: transparent;
  border: 2rpx solid #4e6ef2;
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
}

.try-button text {
  color: #4e6ef2;
  font-size: 30rpx;
}

.fab {
  position: fixed;
  bottom: 200rpx;
  right: 30rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #4e6ef2;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 10rpx rgba(78, 110, 242, 0.3);
  z-index: 10;
}

.fab-icon {
  color: white;
  font-size: 50rpx;
  font-weight: 300;
}
</style>
